import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'soil',
        component: () => import('@/views/dashboard/LeftComponets/SoilMonitor.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  console.log('Current route:', to.path)
  console.log('Token exists:', !!token)

  // 不需要验证的路由
  const publicPages = ['/login', '/register']
  const isPublicPage = publicPages.includes(to.path)

  if (to.path === '/') {
    // 根路径重定向到登录页
    console.log('Root path, redirecting to login')
    next('/login')
    return
  }

  if (!token && !isPublicPage) {
    // 没有token且访问非公共页面，重定向到登录页
    console.log('No token, redirecting to login')
    next('/login')
    return
  }

  // 其他情况正常放行
  console.log('Proceeding to:', to.path)
  next()
})

export default router
